package com.jch.mp.manner1.codec;

import com.jch.mp.manner1.domain.protocol.PacketClassMap;
import com.jch.mp.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MsgDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 8) { // 固定标识 + 数据包长度（子协议标识长度 + 数据长度）
            return;
        }
        in.markReaderIndex();
        in.skipBytes(4);// 跳过固定标识 9527
        int length = in.readInt();
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        byte command = in.readByte(); // 解析协议标识 1：simple 2：group 3：complex
        byte[] data = new byte[length - 1];
        in.readBytes(data);
        out.add(SerializationUtil.deserialize(data, PacketClassMap.packetTypeMap.get(command)));
    }
}
